<template>

  <el-main>
    <!--条件查询-->
    <el-form ref="searchForm" 
    :model="searchModel" 
    label-width="80px"  
    :inline="ture" 
    size="small">
      <el-form-item>
        <el-input v-model="searchModel.roleName" placeholder="请输入角色名称" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="search(pageNo,pageSize)">查询</el-button>
        <el-button icon="el-icon-refresh-right" @click="resetValue">重置</el-button>
        <el-button type="success" icon="el-icon-plus" >新增</el-button>
      </el-form-item>
    </el-form>
    <!--数据表格-->
    <el-table :data="roleList" :height="tableHeight" border stripe style="width: 100%; margin-bottom: 10px">
      <el-table-column label="角色编号" prop="id" width="100" align="center" />
      <el-table-column prop="roleName" label="角色名称" />
      <el-table-column prop="remark" label="角色备注" />
      <el-table-column label="操作" align="center" width="290">
        <template slot-scope="scope">
          <el-button icon="el-icon-edit" type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button icon="el-icon-delete" type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
          <el-button icon="el-icon-setting" type="primary" size="small" @click="assignRole(scope.row)">分配权限</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页工具栏 -->
    <el-pagination
      background
      :current-page="pageNo"
      :page-sizes="[10, 20, 30, 40, 50]"
      :page-size="10"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <!-- 添加和编辑部门窗口 -->
    <system-dialog
      :title="roleDialog.title"
      :visible="roleDialog.visible"
      :width="roleDialog.width"
      :height="roleDialog.height"
      @onClose="onClose"
      @onConfirm="onConfirm"
    >
      <div slot="content">
        <el-form
          ref="roleForm"
          :model="role"
          :rules="rules"
          label-width="80px"
          :inline="false"
          size="small"
        >
          <el-form-item label="角色编码" prop="roleCode">
            <el-input v-model="role.roleCode"></el-input>
          </el-form-item>
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="role.roleName" />
          </el-form-item>
          <el-form-item label="角色描述">
            <el-input type="textarea" v-model="role.remark" :rows="5"></el-input>
          </el-form-item>
        </el-form>
      </div>
    </system-dialog>
    <system-dialog
      :title="assignDialog.title"
      :visible="assignDialog.visible"
      :width="assignDialog.width"
      :height="assignDialog.height"
      @onClose="onAssignClose"
      @onConfirm="onAssignConfirm"
    >
      <div slot="content">
        <el-tree
          ref="assignTree"
          :data="assignTreeData"
          node-key="id"
          :props="defaultProps"
          empty-text="暂无数据"
          :show-checkbox="true"
          :highlight-current="true"
          default-expand-all
        ></el-tree>
      </div>
    </system-dialog>
  </el-main>
</template>

<script>
import roleApi from '@/api/role';
// 导入对话框组件
import SystemDialog from '@/components/system/SystemDialog.vue'
import leafUtils from '@/utils/leaf'
export default {
  name: 'roleList',
  // 组件注册
  components: {
    SystemDialog
  },
  data() {
    return {
      assignDialog: {
        title: '',
        visible: false,
        height: 450,
        width: 300
      },
      rules:{
        roleCode: [{ required: true, trigger: 'blur', message: '请输入角色编码' }],
        roleName: [{ required: true, trigger: 'blur', message: '请输入角色名称' }]
      },
      roleDialog: {
        title: '',
        visible: false,height: 230,
        width: 500
      },
      role:{
        id:"",
        roleCode:"",
        roleName:"",
        remark:"",
        createUser:this.$store.getters.userId
      },
    // 查询条件
      searchModel: {
        roleName: '',
        pageNo:1,
        pageSize:10,
        userId:this.$store.getters.userId
      },
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      assignTreeData: [],
      roleList: [], // 数据列表
      tableHeight: 0, // 表格高度
      pageNo: 1, // 当前页码
      pageSize: 10, // 每页显示数量
      total: 0, // 总数量
      roleId: '', //角色ID
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.tableHeight = window.innerHeight - 220
    })
  },
  created() {
    this.search();
  },
  methods: {
    onClose() {
      this.roleDialog.visible = false
    },
    onConfirm() {
      this.$refs.roleForm.validate(async (valid)=>{
        if(valid){
          let res = null;
          if (this.role.id === "") {
            res = await roleApi.addRoleApi(this.role);
          }else{
            res = await roleApi.updateRoleApi(this.role);
          }
          if (res.success) {
            this.$message.success(res.message);
            this.search(this.pageNo,this.pageSize);
            this.roleDialog.visible = false;
          }else{
            this.$message.error(res.message);
          }
        }
      });
    },
    /**
    * 查询
    */
    async search(pageNo=1,pageSize=10) {
      this.searchModel.pageNo = pageNo;
      this.searchModel.pageSize = pageSize;
      let res = await roleApi.getRoleListApi(this.searchModel);
      if (res.success) {
        this.roleList = res.data.records;
        this.total = res.data.total;
      }
    },
    /**
    * 重置查询条件
    */
    resetValue() {
      this.searchModel.roleName="";
      this.search();
    },
    /**
    * 当每页数量发生变化时触发该事件
    */
    handleSizeChange(size) {
      this.pageSize = size;
      this.search(this.pageNo, size);
    },
    /**
    * 当页码发生变化时触发该事件
    */
    handleCurrentChange(page) {
      this.pageNo = page;
      this.search(page, this.pageSize);
    },
    openAddWindow() {
      this.$resetForm("roleForm",this.role);
      this.roleDialog.title = '新增角色'//设置窗口标题
      this.roleDialog.visible = true//显示窗口
    },
    /**
    * 打开编辑窗口
    */
    handleEdit(row) {
      this.$objCopy(row, this.role); //将当前编辑的数据复制到role对象中
      this.roleDialog.title = "编辑角色";
      this.roleDialog.visible = true;
    },
    /**
    * 删除
    */
    handleDelete(row) {
    },
    async assignRole(row){
      this.roleId = row.id
      let params = {
        roleId: row.id,
        userId: this.$store.getters.userId
      }
      let res = await roleApi.getAssignTreeApi(params)
      if (res.success) {
        let permissionList = res.data.permissionPOList
        let checkList = res.data.checkList
        let { setLeaf } = leafUtils()
        let newPermissionList = setLeaf(permissionList)
        this.assignTreeData = newPermissionList
        this.$nextTick(() => {
          let nodes = this.$refs.assignTree.children
          this.setChild(nodes, checkList)
        })
      }
      this.assignDialog.visible = true
      this.assignDialog.title = `给【${row.roleName}】分配权限`
    },
    setChild(childNodes, checkList) {
      if (childNodes && childNodes.length > 0) {
        for (let i = 0; i < childNodes.length; i++) {
          let node = this.$refs.assignTree.getNode(childNodes[i])
          if (checkList && checkList.length > 0) {
            for (let j = 0; j < checkList.length; j++) {
              if (checkList[j] == childNodes[i].id) {
                if (childNodes[i].open) {
                  this.$refs.assignTree.setChecked(node, true)
                  break
                }
              }
            }
          }
          if (childNodes[i].children) {
            this.setChild(childNodes[i].children, checkList)
          }
        }
      }
    },
    onAssignClose() {
      this.assignDialog.visible = false
    },
    async onAssignConfirm() {
      let ids = this.$refs.assignTree.getCheckedKeys()
      let pids = this.$refs.assignTree.getHalfCheckedKeys()
      let listId = ids.concat(pids)
      let params = {
        roleId: this.roleId,
        list: listId
      }
      let res = await roleApi.assignSaveApi(params)
      if (res.success) {
        this.assignDialog.visible = false
        this.$message.success(res.message)
      }else{
        this.$message.error(res.data)
      }
    }
  }

}

</script>

<style lang="scss" scoped></style>
